<template>
  <div class='sub-category'>
    <div class="container">
      <!-- 面包屑 -->
      <SubBread />

      <!-- 筛选区 -->
      <SubFilter @filter-change="filterChange" />

      <div class="goods-list">
        <!-- 排序 -->
        <SubSort @sort-change="sortChange" />
        <!-- 列表 -->
        <ul>
          <li v-for="goods in goodsList" :key="goods.id">
            <GoodsItem :goods="goods" />
          </li>
        </ul>
        <XtxInfiniteLoading :loading="loading" :finished="finished" @infinite="getData" />
      </div>
    </div>
  </div>
</template>

<script>
import SubBread from './components/SubBread'
import SubFilter from './components/SubFilter'
import SubSort from './components/SubSort'
import GoodsItem from './components/GoodsItem'
import { ref, watch } from 'vue'
import { findSubCategotyGoodsAPI } from '@/api/category'
import { useRoute } from 'vue-router'

export default {
  name: 'SubCategory',
  components: {
    SubBread,
    SubFilter,
    SubSort,
    GoodsItem
  },

  setup () {
    const route = useRoute()
    // 加载中
    const loading = ref(false)
    // 是否加载完毕
    const finished = ref(false)
    const goodsList = ref([])
    let reqParams = {
      page: 1,
      pageSize: 20
    }
    const getData = () => {
      loading.value = true
      reqParams.categoryId = route.params.id
      findSubCategotyGoodsAPI(reqParams).then(data => {
        if (data.result.items.length === 0) {
          finished.value = true
          loading.value = false
          return
        }
        goodsList.value = [...goodsList.value, ...data.result.items]
        reqParams.page++
        loading.value = false
      })
    }

    // 切换路径后
    watch(() => route.params.id, (newValue) => {
      if (newValue && `/category/sub/${newValue}` === route.path) {
        goodsList.value = []
        reqParams.page = 1
        finished.value = false
      }
    }, { immediate: true })

    function sortChange (sortParams) {
      finished.value = false
      reqParams.page = 1
      goodsList.value = []
      reqParams = { ...reqParams, ...sortParams }
    }

    function filterChange (filterParams) {
      finished.value = false
      reqParams.page = 1
      goodsList.value = []
      reqParams = { ...reqParams, ...filterParams }
    }

    return {
      getData, loading, finished, goodsList, sortChange, filterChange
    }
  }
}
</script>
<style scoped lang="less">

.goods-list {
  background: #fff;
  padding: 0 25px;
  margin-top: 25px;

  ul {
    display: flex;
    flex-wrap: wrap;
    padding: 0 5px;

    li {
      margin-right: 20px;
      margin-bottom: 20px;

      &:nth-child(5n) {
        margin-right: 0;
      }
    }
  }
}
</style>
